package edu.neepu;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.*;
public class MainClass {
    public static void downloadImage(String imgUrl,String imgName) throws UnsupportedEncodingException {
        String filePath="f:/image";//图片下载后的存储路径
        String fileName = imgName;//图片名
        File file = new File(filePath+File.separator+fileName+".jpg");//创建文件
        try{
            URL url = new URL(imgUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setConnectTimeout(10 * 1000);
            DataInputStream dataInputStream = new DataInputStream(urlConnection.getInputStream());
            DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(file));
            byte b [] = new byte[4096];
            int size;
            while((size=dataInputStream.read(b))!=-1){
                dataOutputStream.write(b,0,size);
            }
            dataInputStream.close();
            dataOutputStream.close();
            System.out.println("下载图片："+(fileName+".jpg")+"  成功！");
        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    public void test8(){//下载图片
        try{
            for(int i=1;i<=1;i++){
                System.out.println("第"+i+"页：");
                Document document = Jsoup.connect("https://bing.ioliu.cn/?p="+i).get();
                Elements elements = document.select(".card.progressive");
                for(Element element :elements){
                    Spider spider = new Spider(element);
                    Thread t = new Thread(spider);
                    t.start();
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    public static  void main(String [] args){
        new MainClass().test8();
    }
    class Spider implements  Runnable{
        Element element;
        public Spider(Element element){
            this.element = element;
        }
        public void run() {
            System.out.println("下载地址： "+element.select("a.ctrl.download").attr("abs:href"));
            String imgurl = element.select("a.ctrl.download").attr("abs:href").toString();
            String imgname_e1 = element.select(".location em.t").text();//图片拍摄地点
            String imgname_e2 = element.select(".calendar em.t").text();//图片拍摄的时间
            System.out.println("图片拍摄地点："+imgname_e1+"   图片拍摄时间："+imgname_e2);
            try {
                MainClass.downloadImage(imgurl,(imgname_e1+imgname_e2));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
